/*
<<<<<<< HEAD
 * @Author: pao
 * @Date:   2016-12-30 18:25:15
 * @Last Modified by:   pao
 * @Last Modified time: 2017-01-04 19:47:35
 */

'use strict';

const express = require('express');
const path = require('path');
const app = express();
//处理静态资源的加载
app.use(express.static('./static'));

const orm = require('orm');
//连接数据库
app.use(orm.express('mysql://root:751189277@127.0.0.1/nodeproject', {
    define: (db, models, next) => {
        //建立模型，映射到数据库
        models.user = db.define('vms_user', {
            uid: { type: 'serial', key: true },
            uname: String,
            upwd: String,
            ustate: Number
        });
        models.video = db.define('vms_video', {
            vid: { type: 'serial', key: true },
            vtitle: String,
            vsortno: Number,
            vvideoid: Number,
            vsummary: String,
            vimgurl: String,
            vremark: String
        });
        console.log('连接数据库成功');
        next();
    }
}));

//导入生成session的第三方包
const session = require('express-session');
app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true
        // cookie: { secure: true }//用于https
}))

const bodyParser = require('body-parser');
//调用bodyParser中urlencoded的方法,使表单提交的参数添加到req.body上
app.use(bodyParser.urlencoded({ extended: true }));
//用于ajax请求，将post请求体的参数转化成json对象并添加到req.body上
app.use(bodyParser.json());

//权限验证
app.all('/video/*', (req, res, next) => {
    if (req.session.uname) {
        next();
    } else {
        res.end("<script>alert('请先登录');window.location='/account/login'</script>")
    }
});


//引入登录页面路由模块
const loginRoute = require('./router/loginRoute.js');
//引入视频列表页路由模块
const videoListRoute = require('./router/videoListRoute.js');

//登录页面的路由
app.use('/account', loginRoute);
//视频列表页的路由
app.use('/video', videoListRoute);


const ueditor = require("ueditor");

//处理ueditor上传图片等媒体资源的路由
app.use("/ueditor/ue", ueditor(path.join(__dirname, 'static'), function(req, res, next) {
    //客户端上传文件设置
    var ActionType = req.query.action;
    if (ActionType === 'uploadimage' || ActionType === 'uploadfile' || ActionType === 'uploadvideo') {
        var file_url = '/img/ueditor/'; //默认图片上传地址
        /*其他上传格式的地址*/
        if (ActionType === 'uploadfile') {
            file_url = '/file/ueditor/'; //附件
        }
        if (ActionType === 'uploadvideo') {
            file_url = '/video/ueditor/'; //视频
        }
        res.ue_up(file_url); //你只要输入要保存的地址 。保存操作交给ueditor来做
        res.setHeader('Content-Type', 'text/html');
    }
    //  客户端发起图片列表请求
    else if (req.query.action === 'listimage') {
        var dir_url = '/images/ueditor/';
        res.ue_list(dir_url); // 客户端会列出 dir_url 目录下的所有图片
    }
    // 客户端发起其它请求
    else {
        // console.log('config.json')
        res.setHeader('Content-Type', 'application/json');
        res.redirect('/ueditor/nodejs/config.json');
    }
}));


app.listen(8090, '127.0.0.1', () => {
    console.log('ok');
})
